# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '9999103': {  # 新支付  微信扫码10-500 3.8%  快捷0-5000 1.5%  支付宝10-5000   3% dwc
        'API_KEY': 'H9B0h85b7Rw99L29Cv6W',
        'gateway': 'http://buy.shengcaifu.hk/order/payorder',
        'query_gateway': 'http://buy.shengcaifu.hk/transfer/querypayorder',
        'APP_NO': '10015',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_app_no(mch_id):
    return APP_CONF[mch_id]['APP_NO']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and k != 'payinfo' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    return _gen_sign(s)


def verify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("xinwirelesspay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'wechat':
        return 1
    elif service == 'alipay':
        return 2
    elif service == 'alipay_wap':
        return 2
    elif service == 'unionpay':
        return 3
    elif service == 'qq':
        return 4
    return 1


def _get_ablity_type(service):
    if service == 'wechat':
        return 2
    elif service == 'alipay':
        return 2
    elif service == 'alipay_wap':
        return 3
    elif service == 'unionpay':
        return 5
    elif service == 'qq':
        return 4
    return 1


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantno', app_id),
        ('appno', _get_app_no(app_id)),
        ('paytype', _get_pay_type(service)),
        ('paymode', _get_ablity_type(service)),
        ('merchantorder', str(pay.id)),
        ('amount', '%.2f' % pay_amount),
        ('currency', 'RMB'),
        ('itemno', '1'),
        ('itemname', 'charge'),
        ('customerno', str(pay.user_id)),
        ('notifyurl', '{}/pay/api/{}/xinwirelesspay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('payinfo', 'CCB'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("xinwirelesspay create: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/json'}
    response = requests.post(_get_gateway(app_id), json=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('xinwirelesspay create rsp, %s', response.text)
    verify_sign(json.loads(response.text), api_key)
    return {'charge_info': json.loads(response.text)['url']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("xinwirelesspay notify data: %s", dict(request.POST.iteritems()))
    data = dict(request.POST.iteritems())
    data_trans = json.loads(unicode(data.keys()[0]))
    verify_sign(data_trans, api_key)
    pay_id = data_trans['merchantorder']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('xinwirelesspay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data_trans['status'])
    trade_no = data_trans['transid']
    total_fee = float(data_trans['amount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 订单状态：
    # 1-正在支付
    # 2-支付成功
    # 3-支付失败
    if trade_status == '2' and total_fee > 0.0:
        _LOGGER.info('xinwirelesspay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantno', app_id),
        ('appno', _get_app_no(app_id)),
        ('merchantorder', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('xinwirelesspay query data is: %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['merchantorder'])
    headers = {'Content-Type': 'application/json'}
    response = requests.post(_get_query_gateway(app_id), json=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('xinwirelesspay query rsp: %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['status'])
        total_fee = float(data['amount'])
        trade_no = data['serialno']
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        # 订单状态： 1-正在支付，2-支付成功，3-支付失败，4-延迟支付
        if trade_status == '2':
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('xinwirelesspay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
